<template>
    <div style="width: 100%;height: 100%;background: white">
        <div class="filter-component">
            <div :class="{ 'filter-1':paramMapping.stylize==1,'filter-2':paramMapping.stylize==2,'filter-3':paramMapping.stylize==3,'filter-4':paramMapping.stylize==4,'filter-5':paramMapping.stylize==5}"
                 v-for="(paramMapping,index) in filter.publish.paramMapping">
                <div :class="[filter.layout=='standard'?'filter-component-list':'filter-component-list-vertical']">
                    <div  :class="[filter.layout=='standard'?'filter-component-list-le':'']">{{paramMapping.label}}</div>
                    <div  :class="[filter.layout=='standard'?'filter-component-list-ri':'filter-component-list-ri-vertical']">
                        <a-input v-if="paramMapping.type=='text'" v-model:value="paramMapping.value"
                                 @change="onChange(paramMapping)"
                                 allowClear></a-input>
                        <a-input type="number" v-else-if="paramMapping.type=='number'" v-model:value="paramMapping.value"
                                 @change="onChange(paramMapping)"/>
                        <a-select style="width: 100%" v-if="paramMapping.type=='select'"
                                  :mode="paramMapping.settings.multiSelect?'multiple':'default'"
                                  allowClear v-model:value="paramMapping.value"
                                  @change="onChange(paramMapping)" :options="optionObj[paramMapping.key]"></a-select>
                        <a-month-picker
                            style="width: 100%"
                            v-else-if="paramMapping.type=='month'"
                            format="YYYY-MM"
                            @change="dateChange($event,paramMapping,'YYYY-MM')"
                            v-model:value="paramMapping.value"
                            />
                        <a-date-picker
                            style="width: 100%"
                            v-else-if="paramMapping.type=='year'"
                            picker="year"
                            @change="dateChange($event,paramMapping,'YYYY')"
                            v-model:value="paramMapping.value"
                        />
                        <a-date-picker
                            style="width: 100%"
                            v-model:value="paramMapping.value"
                            @change="dateChange($event,paramMapping,'YYYY-MM-DD')"
                            v-else-if="paramMapping.type=='date'"
                            :locale="locale"
                            :show-time="paramMapping.settings.format=='YYYY-MM-DD HH:mm:ss'"
                            :format="paramMapping.settings.format || 'YYYY-MM-DD'"
                        />
                        <a-range-picker
                            style="width: 100%"
                            :value="getRangeDate(paramMapping)"
                            v-else-if="paramMapping.type=='dateRange'"
                            @change="rangeDateChange($event,paramMapping)"
                        />
                        <rx-input-button v-else-if="paramMapping.type=='dialog'"
                                         @change="onChange(paramMapping)" v-model="paramMapping.value"
                                         @btnClick="openDialog($event,paramMapping)"/>
                        <rx-user-component v-else-if="paramMapping.type=='user'" v-model="paramMapping.values"
                                           @change="onChange(paramMapping)" :single="!paramMapping.settings.multiSelect" :readonly="false"  style="width:100%"></rx-user-component>
                        <rx-group-component v-else-if="paramMapping.type=='group'" v-model="paramMapping.values"
                                            :single="!paramMapping.settings.multiSelect" @change="onChange(paramMapping)"></rx-group-component>
                        <rx-tree-select-ctl class="filt-tree"  v-else-if="paramMapping.type=='tree'" v-model="paramMapping.values"
                                            :multiValue="false" :labelInValue="false" :toTree="false" :multiSelect="paramMapping.settings.multiSelect"
                                            :dataSource="optionObj[paramMapping.key]" style="width: 100%"/>
                    </div>
                </div>
            </div>
            <div class="filter-button" v-show="filter.showButton">
                <a-button type="primary" @click="search()">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    {{$ti18('rxList.searchBtn','查询')}}
                </a-button>
                <a-button style="margin-left: 4px" @click="reset">
                    <template #icon>
                        <RedoOutlined />
                    </template>
                    {{$ti18('rxList.resetBtn','重置')}}
                </a-button>
            </div>
        </div>
    </div>
</template>

<script>
/**
 * 自定义页面(筛选器组件)
 */
import {debounce} from "lodash-es";
import FormApi from "@/common/api/form/FormApi.js";
import {Util,RxInputButton,RxTreeSelectCtl} from "@lowcode/jpaas-base-lib";
import BusEvent from "../BusEvent.js";
import {RxUserComponent,RxGroupComponent,ShareDialog} from "@lowcode/jpaas-share-component"
import dayjs from 'dayjs';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
export default {
    name: "filterView",
    components: {RxInputButton,RxUserComponent,RxGroupComponent,RxTreeSelectCtl},
    mixins:[BusEvent],
    props: {
        config:{
            type:Object,
            default:()=>{
                return {}
            }
        }
    },
    data() {
        return {
            locale,
            //筛选器
            filter: {},
            //下拉框数据
            optionObj:{}
        }
    },
    created() {
        this.initConfig();
    },
    mounted(){
        let self = this;
        this.$nextTick(function (){
            setTimeout(function(){
                self.initParamMapping(false)//执行方法
            },500)
        })
    },

    methods: {
        initConfig() {
            this.filter = JSON.parse(JSON.stringify(this.config));
            this.initOptions();
        },
        //构建参数并触发事件
        initParamMapping(reset) {
            let paramMappings = this.filter.publish.paramMapping;
            let params = {};
            for (let i = 0; i < paramMappings.length; i++) {
                let paramMapping = paramMappings[i];
                if (reset) {
                    paramMapping.value = "";
                    if(paramMapping.values){
                        paramMapping.values=[];
                    }
                }
                if((paramMapping.type=='user' || paramMapping.type=='group') && paramMapping.values){
                    let ary=[];
                    for (let i = 0; i < paramMapping.values.length; i++) {
                        ary.push(paramMapping.values[i].id);
                    }
                    params[paramMapping.key]=ary.join(",");
                }else if(paramMapping.type=='tree'){
                    params[paramMapping.key]=Array.isArray(paramMapping.values)?paramMapping.values.join(","):paramMapping.values;
                }else if(paramMapping.type=='date'){
                    params[paramMapping.key] =paramMapping.value?dayjs(paramMapping.value).format(paramMapping.settings.format || 'YYYY-MM-DD'):''
                }else if(paramMapping.type=='month'){
                    params[paramMapping.key] =paramMapping.value?dayjs(paramMapping.value).format('YYYY-MM'):''
                }else if(paramMapping.type=='year'){
                    params[paramMapping.key] =paramMapping.value?dayjs(paramMapping.value).format('YYYY'):''
                }else if(paramMapping.type=='dateRange' && paramMapping.value){
                    let item = []
                    paramMapping.value.map(vl=>{
                        item.push(vl?dayjs(vl).format(paramMapping.settings.format || 'YYYY-MM-DD'):'')
                    })
                    params[paramMapping.key] = item
                }else{
                    params[paramMapping.key] = paramMapping.value || "";
                }
            }
            //触发事件
            this.handEvent(params);
        },
        onChange: debounce(function (paramMapping) {
            //查找下拉框是否配置当前为参数
            this.findSelectParams(paramMapping);
            //未配置按钮则直接触发事件
            if (!this.filter.showButton) {
                this.initParamMapping(false);
            }
        }, 500),
        //触发事件
        handEvent(params) {
            this.$bus.emit("formCustomViewEvent", {component: this.config.alias, params: params});
        },
        search() {
            this.initParamMapping(false);
        },
        reset() {
            this.initParamMapping(true);
        },
        initOptions(){
            //下拉框获取选项数据
            for (let i = 0; i < this.filter.publish.paramMapping.length; i++) {
                let paramMapping = this.filter.publish.paramMapping[i];
                if(paramMapping.value && paramMapping.type == "date"){
                    paramMapping.value = dayjs(paramMapping.value,paramMapping.settings.format || 'YYYY-MM-DD')
                }else if(paramMapping.value && paramMapping.type=='month'){
                    paramMapping.value = dayjs(paramMapping.value,'YYYY-MM')
                }else if(paramMapping.value && paramMapping.type=='year'){
                    paramMapping.value = dayjs(paramMapping.value,'YYYY')
                }
                if (paramMapping.settings && (paramMapping.type == "select" || paramMapping.type == "tree")) {
                    this.getOptions(paramMapping.settings,paramMapping.key,"",paramMapping.type);
                    if(paramMapping.settings.multiSelect){
                        paramMapping.value = [];
                    }
                }
            }
        },
        getOptions(settings,key,params,type){
            if(!settings){
                return;
            }
            let options = [];
            //自定义
            if(settings.from=="self"){
                let dataSource = settings.dataSource;
                for (let j = 0; j < dataSource.length; j++) {
                    options.push({
                        value:dataSource[j].key,
                        label:dataSource[j].name,
                    })
                }
                this.optionObj[key]=options;
            }
            //数据字典
            else if(settings.from=="dic"){
                FormApi.loadDicByPidAndDicId(settings.dicKey,"").then(res=>{
                    if(res.length && res.length>0){
                        for (let j = 0; j < res.length; j++) {
                            options.push({
                                id:res[j].pkId,
                                value:res[j].value,
                                label:res[j].name,
                                parentId:res[j].parentId,
                            })
                        }
                    }
                    if(type=='tree'){
                        options=Util.listToTree(options, "id", "parentId");
                    }
                    this.optionObj[key]=options;
                });
            }
            //sql
            else if(settings.from=="sql"){
                if(!settings.sql){
                    return;
                }
                let textfield=settings.sql_textfield;
                let valuefield=settings.sql_valuefield;
                let parentfield=settings.sql_parentfield;
                let sql=JSON.parse(settings.sql).value;
                FormApi.queryForJson(sql, {params: params}).then(res=>{
                    let data=res.data;
                    if(data.length && data.length>0) {
                        for (let j = 0; j < data.length; j++) {
                            options.push({
                                value:data[j][valuefield],
                                label:data[j][textfield],
                                parentId:data[j][parentfield],
                            })
                        }
                    }
                    if(type=='tree'){
                        options=Util.listToTree(options, "value", "parentId");
                    }
                    this.optionObj[key]=options;
                });
            }
            //权限数据
            else if(settings.from=="grant"){
                if(settings.grant){
                    let grant=JSON.parse(settings.grant).value;
                    FormApi.loadByGrant(grant).then(res => {
                        for (let j = 0; j < res.data.length; j++) {
                            options.push({
                                value:res.data[j]["value"],
                                label:res.data[j]["label"],
                                parentId:res.data[j]["parentId"]
                            })
                        }
                        if(type=='tree'){
                            options=Util.listToTree(options, "value", "parentId");
                        }
                        this.optionObj[key]=options;
                    })
                }
            }
        },
        //查找下拉框是否配置当前为参数
        findSelectParams(paramMapping){
            for (let i = 0; i <this.filter.publish.paramMapping.length; i++) {
                let mapping=this.filter.publish.paramMapping[i];
                //下拉框 自定义查询
                if((mapping.type=="select" || mapping.type=="tree") && mapping.settings.from=='sql'){
                    for (let j = 0; j < mapping.settings.paramsData.length; j++) {
                        let paramsData=mapping.settings.paramsData[j];
                        if(paramMapping.key==paramsData.bindVal){
                            let params={};
                            params[paramsData.fieldName]=paramMapping.value;
                            this.getOptions(mapping.settings,mapping.key,JSON.stringify(params),mapping.type);
                        }
                    }
                }
            }
        },
        dateChange(value,paramMapping,format){
            paramMapping.value=value?dayjs(value,paramMapping.settings.format || format):'';
        },
        rangeDateChange(values,paramMapping){
            let ary=[];
            if(!values){
                paramMapping.value = ''
                return
            }
            ary.push(dayjs(values[0],paramMapping.settings.format || 'YYYY-MM-DD'));
            ary.push(dayjs(values[1],paramMapping.settings.format || 'YYYY-MM-DD'));
            paramMapping.value=ary;
        },
        getDate(paramMapping){
            if(!paramMapping.value){
                return "";
            }
            let date=dayjs(paramMapping.value,paramMapping.settings.format || 'YYYY-MM-DD');
            return  date || "";
        },
        getRangeDate(paramMapping){
            if(!paramMapping.value){
                return [];
            }
            let ary = [];
            ary.push(dayjs(paramMapping.value[0],paramMapping.settings.format||'YYYY-MM-DD'));
            ary.push(dayjs(paramMapping.value[1],paramMapping.settings.format||'YYYY-MM-DD'));
            return  ary;
        },
        openDialog(vm,paramMapping){
            let settings=paramMapping.settings;
            let dialog=settings.dialog;
            let valueField=settings.valueField;
            let textField=settings.textField;
            let single=!settings.multiSelect;
            if(!dialog){
                this.$message.error(vm.$ti18('rxMsa.masWarn.configDialog',"请配置对话框"));
                return;
            }
            let self=this;
            let dialogKey=JSON.parse(dialog).value;
            ShareDialog.dialog({key:dialogKey,single:single},{curVm: self},function(data){
                if(data.rows.length==0){
                    return;
                }
                let values=[];
                let texts=[];
                //多选
                if(data.multiSelect) {
                    for (let i = 0; i <  data.rows.length; i++) {
                        values.push( data.rows[i][valueField]);
                        texts.push( data.rows[i][textField]);
                    }
                }else{
                    values.push(data.rows[0][valueField]);
                    texts.push(data.rows[0][textField]);
                }
                vm.setVal(values.join(','),texts.join(','));
                paramMapping.value=values.join(',');
            });
        }
    },
    watch: {
        config: {
            handler: function (val, oldVal) {
                if (val) {
                    this.initConfig();
                }
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.filter-button{
    margin-left: 20px;
    margin-top: 8px;
    display: flex;
    align-items: flex-end;
}
.filter-component >>>.ant-select-tree{
    max-height: 400px!important;
    overflow: auto;
    margin-top: 10px;
}
.filter-component-list-vertical{
    margin-left: 20px;
    margin-top: 15px;
}
.filter-component-list-ri-vertical{
    margin-top: 8px;
    margin-right: 10px;
}
.filter-component-list{
    display: flex;
    align-items: center;
    line-height: 30px;
    margin-right: 10px;
    margin-top: 15px;
}
.filter-component-list-le{
    width:20%;
    text-align: right;
    margin-right: 10px
}
.filter-component-list-ri{
    flex: 1;
    margin-right: 10px;
    display: flex;
    align-content: center;
}
.filter-component{
    display: flex;
    flex-wrap: wrap;
}
.filter-1{
    flex: 0 0 25% !important;
}
.filter-2{
    flex: 0 0 33.33% !important;
}
.filter-3{
    flex: 0 0 66.66% !important;
}
.filter-4{
    flex: 0 0 50% !important;
}
.filter-5{
    flex: 0 0 100% !important;
}
.filter-component>>>.ant-select-selection__rendered{
    height: 30px!important;
    overflow: hidden!important;
}
.filter-component>>>.ant-select-selection__rendered > ul > li{
    max-width: 120px;
}
</style>
